package com.nikolaj.kuzan.dao;

import java.io.*;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;

/**
 * Created by Nikolay on 29.04.14.
 */
public class CsvFileDao implements FileDAO {

    private String csvDataSeparator;

    public CsvFileDao() {
        csvDataSeparator = ";";
    }

    @Override
    public Map<Double, Double> getDataForProcess(File dataFile) throws IOException {

        if (dataFile == null){
            throw new RuntimeException("Невозможно открыть файл.");
        }

        Map<Double, Double> result = new TreeMap<>();

        try {
            BufferedReader br = new BufferedReader(new BufferedReader(
                    new FileReader(dataFile)));
            String sCurrentLine = "";
            String[] xy = new String[2];
            while ((sCurrentLine = br.readLine()) != null) {
                xy = sCurrentLine.split(csvDataSeparator);
                result.put(Double.parseDouble(xy[0]), Double.parseDouble(xy[1]));
            }
            br.close();
        } catch (FileNotFoundException e) {
            throw new FileNotFoundException("Не удалось открыть файл с данными.");
        } catch (NumberFormatException e) {
            throw new RuntimeException("Невозможно преобразовать данные. Ошибка в CSV-файле");
        } catch (IOException e) {
            throw new IOException("Не удалось открыть файл с данными.");
        }
        return result;
    }

    @Override
    public Map<Double, Double> getAnalyzedDataForShowInChart(File dataFile) throws IOException {
        return null;
    }

    @Override
    public void saveData(Map<Integer, Integer> data, String path) {

        BufferedWriter out;

        if (!path.endsWith(".csv")) {
            throw new RuntimeException(
                    "Wrong file format. Please, type correct file extention");
        }

        try {

            FileWriter fstream = new FileWriter(path, true);
            out = new BufferedWriter(fstream);
            int count = 0;
            Iterator<Map.Entry<Integer, Integer>> it = data.entrySet().iterator();
            while (it.hasNext() && count < data.size()) {
                Map.Entry<Integer, Integer> pairs = it.next();

                out.write(pairs.getKey() + this.csvDataSeparator);
                out.write(pairs.getValue() + "\n");
                count++;
            }
            out.close();
        } catch (IOException e) {
            throw new RuntimeException("Cann't write data to the file");
        }
    }
}
